//
//  BCIndustryAllController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/19.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "BCIndustryAllController.h"

#import "UINavigationController+QMUI.h"

#import "BCProjectDetailsController.h"//项目明细

//筛选的视图
#import "BCIndustryScreeningView.h"

//cell
#import "BCIndustryAllCell.h"

//model
#import "BCProjectModel.h"

//refresh
#import "BCRefreshNormalHeader.h"
#import "BCRefreshAutoFooter.h"


//request
#import "BCAllIndustryDataRequest.h"

@interface BCIndustryAllController () <BCIndustryScreeningViewDelegate,UITableViewDataSource,UITableViewDelegate>

/**
 是否筛选中的flag
 */
@property (nonatomic, assign) BOOL isScreeningFlag;

/**
 *BCIndustryScreeningView
 */
@property (nonatomic, strong) BCIndustryScreeningView *screeningView;

/**
 *table
 */
@property (nonatomic, strong) UITableView *tableView;

/**
 *refreshHeader
 */
@property (nonatomic, strong) BCRefreshNormalHeader *refreshHeader;
/**
 *refreshAutoFooter
 */
@property (nonatomic, strong) BCRefreshAutoFooter *refreshAutoFooter;


/**
 *dataSource
 */
@property (nonatomic, strong) NSMutableArray *dataSource;

/**
 *page 请求的页面
 */
@property (nonatomic, assign) NSInteger reqeustPage;

@end

@implementation BCIndustryAllController

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (BCIndustryScreeningView *)screeningView {
    if (!_screeningView) {
        _screeningView = [BCIndustryScreeningView new];
        _screeningView.alpha = 0;
        _screeningView.delegate = self;
        [self.view addSubview:_screeningView];
        [_screeningView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.customNaviBar.mas_bottom);
            make.left.bottom.right.mas_equalTo(self.view);
        }];
        [self.view layoutIfNeeded];
    }
    return _screeningView;
}

- (BCRefreshNormalHeader *)refreshHeader {
    if (!_refreshHeader) {
        _refreshHeader = [BCRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshHeaderAction)];
    }
    return _refreshHeader;
}

- (BCRefreshAutoFooter *)refreshAutoFooter {
    if (!_refreshAutoFooter) {
        _refreshAutoFooter = [BCRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshAutoFooterLoadMoreAction) needBottomSafeArea:true];
    }
    return _refreshAutoFooter;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self setupSubviews];
    
    //
    [self.refreshHeader beginRefreshing];
}

- (void)setupSubviews {
    self.customNaviBar.rightButton.imagePosition = QMUIButtonImagePositionRight;
    self.customNaviBar.rightButton.spacingBetweenImageAndTitle = 0;
    [self.customNaviBar.rightButton setImage:[LOAD_IMAGE(@"industry_screening") imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    self.customNaviBar.rightButton.alpha = 0;
    self.customNaviBar.rightButton.tintColor = [UIColor qmui_colorWithHexString:@"#666666"];
    //
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:BCIndustryAllCell.class forCellReuseIdentifier:NSStringFromClass(BCIndustryAllCell.class)];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.customNaviBar.mas_bottom);
        make.left.bottom.right.mas_equalTo(self.view);
    }];
    //
    [self.tableView setMj_header:self.refreshHeader];
    //
    [self.view layoutIfNeeded];
}


- (void)didClickedNaviRightButton {
    self.isScreeningFlag = !_isScreeningFlag;
}

#pragma mark -
- (void)setIsScreeningFlag:(BOOL)isScreeningFlag {
    _isScreeningFlag = isScreeningFlag;
    //按钮变化
    self.customNaviBar.rightButton.userInteractionEnabled = false;
    [UIView animateWithDuration:0.3 animations:^{
        self.customNaviBar.rightButton.imageView.transform = isScreeningFlag?CGAffineTransformMakeRotation(M_PI):CGAffineTransformIdentity;
        self.customNaviBar.rightButton.tintColor = isScreeningFlag?[UIColor darkMainColor]:[UIColor qmui_colorWithHexString:@"#666666"];
    } completion:^(BOOL finished) {
        
    }];
    //显示筛选视图或者隐藏
    [self showScreeningView:isScreeningFlag];
}
- (void)showScreeningView:(BOOL)show {
    WEAK_SELF
    if (show) {
        self.screeningView.alpha = 1;
        [self.screeningView layoutIfNeeded];
        [self.screeningView showScreeningViewComplete:^{
            wself.customNaviBar.rightButton.userInteractionEnabled = true;
        }];
    }else {
        [self.screeningView hiddenScreeningViewComplete:^{
            wself.screeningView.alpha = 0;
            wself.customNaviBar.rightButton.userInteractionEnabled = true;
        }];
    }
}
#pragma mark - 返回
/// 是否需要拦截系统返回按钮的事件，只有当这里返回YES的时候，才会询问方法：`canPopViewController`
- (BOOL)shouldHoldBackButtonEvent {
    return true;
}
/// 是否可以`popViewController`，可以在这个返回里面做一些业务的判断，比如点击返回按钮的时候，如果输入框里面的文本没有满足条件的则可以弹alert并且返回NO
- (BOOL)canPopViewController {
    return !self.isScreeningFlag;
}

#pragma mark - BCIndustryScreeningViewDelegate
- (void)industryScreeningViewDelegateDidClickedDoneButtonAction {
    [self didClickedNaviRightButton];
    //刷新数据
    self.tableView.contentOffset = CGPointZero;
    self.isLoadedData = false;
    [self.tableView reloadData];
    [self.refreshHeader beginRefreshing];
}
- (void)industryScreeningViewDelegateDidCanceledAction {
    [self didClickedNaviRightButton];
}

#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isLoadedData) {
        return self.dataSource.count;
    }else {
        return 5;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BCProjectModel *model;
    if (self.isLoadedData) {
        model = self.dataSource[indexPath.row];
    }
    BCIndustryAllCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(BCIndustryAllCell.class)];
    cell.tableView = tableView;
    cell.cellData = model;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [BCIndustryAllCell defaultHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BCProjectModel *model;
    if (self.isLoadedData) {
        model = self.dataSource[indexPath.row];
        [self toProjectDetailsAction:model];
    }
}


#pragma mark - refreshHeaderAction
- (void)refreshHeaderAction {
    if (self.isLoadedData) {
        [self requestDataInit:false refresh:true loadMore:false];
    }else {
        [self requestDataInit:true refresh:false loadMore:false];
    }
}
//loadMore
- (void)refreshAutoFooterLoadMoreAction {
    [self requestDataInit:false refresh:false loadMore:true];
}

#pragma mark - request
//
- (void)requestDataInit:(BOOL)init refresh:(BOOL)refresh loadMore:(BOOL)loadMore {
    BCAllIndustryDataRequest *request = [BCAllIndustryDataRequest new];
    request.reg_id = [BCUserManager sharedUser].reg_id;
    if (init||refresh) {
        //
        [self.tableView bc_hidderEmptyData];
        [self.tableView bc_hiddenError];
        //
        self.reqeustPage = 1;
        request.page = [NSString stringWithFormat:@"%@",@(self.reqeustPage)];
    }
    if (loadMore) {
        request.page = [NSString stringWithFormat:@"%@",@(self.reqeustPage+1)];
    }
    if (self.customNaviBar.rightButton.alpha) {//有筛选
        request.cur_id = _screeningView.curId;
        request.risk = _screeningView.risk;
        request.profit = _screeningView.yieldRange;
    }
    WEAK_SELF
    [request didRequestCompleted:^{
        if (init||refresh) {
            [wself.refreshHeader endRefreshing];
        }
        if (loadMore) {
            [wself.refreshAutoFooter endRefreshing];
        }
    }];
    [request didRequestSuccessed:^(id result, id page) {
        wself.reqeustPage = request.page.integerValue;
        //
        BCAllIndustryDataResponse *resp = result;
        [wself reloadData:resp init:init refresh:refresh loadMore:loadMore];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *errorMsg = error.domain;
            [QMUITips showError:errorMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errorMsg]];
            //
            if (init||refresh) {
                [wself.tableView bc_showError:error needRefresh:true refreshTitle:nil target:wself refreshAction:@selector(requestInitErrorAction)];
            }
        }
    }];
    [request requestServer];
}
- (void)requestInitErrorAction {
    [self.tableView bc_hiddenError];
    [self.refreshHeader beginRefreshing];
}
//加载数据
- (void)reloadData:(BCAllIndustryDataResponse *)resp init:(BOOL)init refresh:(BOOL)refresh loadMore:(BOOL)loadMore {
    //做保护 可能在加载更多时 操作了刷新 那么此次加载更多数据不要直接舍弃
    if (loadMore) {
        if (!self.tableView.mj_footer) {
            return;
        }
    }
    //
    [self.tableView bc_hidderEmptyData];
    self.isLoadedData = true;
    if (resp) {
        BCAllIndustryData *data = resp.data;
        //
        self.title = data.flow.title;
        //是否显示筛选按钮
//        if (data.has_screening) {
//            self.customNaviBar.rightButton.alpha = 1;
//            [self.customNaviBar.rightButton setTitle:data.flow.right forState:UIControlStateNormal];
//            //
//            self.screeningView.screeningData = data;
//        }else {
//            [self.customNaviBar.rightButton setTitle:nil forState:UIControlStateNormal];
//            self.customNaviBar.rightButton.alpha = 0;
//        }
        //
        NSArray *projects = data.items.data;
        BCAllIndustryDataItemsText *text = data.items.text;
        if (init||refresh) {
            [self.dataSource removeAllObjects];
            //
            if (projects.count==0) {
                [self.tableView bc_showEmptyDataText:data.flow.not_data detail:nil];
            }else {
                [self.refreshAutoFooter setTitle:data.flow.bottom forState:MJRefreshStateNoMoreData];
                if (data.more) {
                    //加入加载更多控件
                    [self.tableView setMj_footer:self.refreshAutoFooter];
                }else {//可以再次显示没有更多
                    
                }
            }
        }
        if (loadMore) {
            if (!data.more) {
                //显示咩有更多了
                [self.refreshAutoFooter endRefreshingWithNoMoreData];
            }
        }
        if (projects.count) {
            for (int i=0; i<projects.count; i++) {
                BCProjectModel *project = projects[i];
                project.repayCaption = text.repay;
                project.countdownMess = text.mess;
                //
                [self.dataSource addObject:project];
            }
        }
    }
    [self.tableView reloadData];
}







//项目明细
- (void)toProjectDetailsAction:(BCProjectModel *)model {
    BCProjectDetailsController *detail = [BCProjectDetailsController new];
    detail.projectId = [NSString stringWithFormat:@"%@",@(model.project_id)];
    [self.navigationController pushViewController:detail animated:true];
}

@end
